<?php
namespace app\common\logic\home;
use app\common\logic\Tools;
use app\common\model\ImgModel;
use app\common\logic\Qiniu;
use app\common\model\ImgStatusModel;
use app\common\model\MaterialModel;
use app\common\model\MytaskModel;
use app\common\model\ClassprogressModel;

//用户影像接口
class ImageApi
{
    private $begin_time;
    private $end_time;
    private $url = 'fungo.tpddns.cn';
    private $caID;

    public function __construct(){
       
        $this->caID = [
        		1 => '0c13c651-1c41-4a92-b08a-7d9d20b85c2d',
				2  => '8925513e-024b-42ae-846b-7cbc6eca2f4f',
				3 => '11279b5a-2d22-4f68-ad72-e4a8b353ab52',
				4  => '417f1e99-f3d6-43fb-8d5b-2a3e1a93d407',
				5  => '0b462799-9dc9-4472-830e-cf8fdc238570',
				6  => 'c69ff449-e16f-421e-bd57-329419093047',
				7  => 'b0031ef9-4922-490d-ba76-0d0c4b64d4be',
				8 => '78a83fe5-4bbe-4145-ab56-7c63a393cd40',
        	];
    }
    //三个阶段获取
    public function index_0(){
        $this->begin_time = date('Y-m-d 07:00:00');
        $this->end_time = date('Y-m-d 10:40:00');
        $this->index();
    }
    //三个阶段获取
    public function index_1(){
        $this->begin_time = date('Y-m-d 10:40:01');
        $this->end_time = date('Y-m-d 13:00:00');
        $this->index();
    }
    //三个阶段获取
    public function index_2(){
        $this->begin_time = date('Y-m-d 13:00:01');
        $this->end_time = date('Y-m-d 16:00:00');
        $this->index();
    }
    //三个阶段获取
    public function index_3(){
        $this->begin_time = date('Y-m-d 16:00:01');
        $this->end_time = date('Y-m-d 19:00:00');
        $this->index();
    }

    //获取影像
    public function index(){
    
        
        $i_age_from = 0;
        $i_age_to = 100;
        $gender = -1;
        $s_face_road_id = 0;
        $dt_from = urlencode($this->begin_time);
        $dt_to = urlencode($this->end_time);
        $IRace = -1;
        $ISmile = -1;
        $IMonthOpen = -1;
        $IEyeopen = -1;
        $IBread = -1;
        $IEyeglasses = -1;
        $IMask = -1;
        $currentPage = 1;
        $pageSize = 30;
        $userId = 'admin';
        $flag = true;
        $url = "http://".$this->url.":7000/FaceDBService/rest/faceSystemData/getFaceNormal";
        $ImgModel = new ImgModel();
        do{
            $urls = "$url?i_age_from=$i_age_from&i_age_to=$i_age_to&gender=$gender&dt_to=$dt_to&dt_from=$dt_from&IRace=$IRace&ISmile=$ISmile&IMonthOpen=$IMonthOpen&IEyeopen=$IEyeopen&IBread=$IBread&IEyeglasses=$IEyeglasses&IMask=$IMask&currentPage=$currentPage&pageSize=$pageSize&roleId=&userId=$userId&flag=$flag";
            //halt($urls);
            $data = Tools::getHttp($urls);
            $data = json_decode($data,true);
            //dump($currentPage);
            //halt($data['content']);
            if(!empty($data['content'])){
                $datas = [];
                foreach ($data['content']["list"] as $key => $value) {

                    $s_big_path = substr($value['s_big_path'],strpos($value['s_big_path'],':7000/')+5);
           
                    $s_path = substr($value['s_path'],strpos($value['s_path'],':7000/')+5);
                    $datas[$key] = [
                        's_big_path' => $s_big_path,
                        's_path' => $s_path,
                        's_id'=>$value['s_id'],
                        'dt_construction_date' => $value['dt_construction_date'],
                        'begin_time' => $this->begin_time,
                        'end_time' => $this->end_time,
                        'create_time'=>date("Y-m-d H:i:s"),
                    ];
                }
                $ImgModel->saveAll($datas);
            }
            $currentPage++;
            if($currentPage >= 1000){
                break;
            }
        }while (!empty($data['content']));
       
    }

    public function indexs(){
    	$ImgStatusModel = new ImgStatusModel();
        $data_img_status['day'] = date("Y-m-d");
        $ImgStatusModel->save($data_img_status);
    }

    //以图搜图
    public function discern($picPath,$beginTime,$endTime,$id){
        $uuid = '8a9d3c1d-4487-4fb4-8c42-e0590fc_'.$id;
        $urlss = 'http://'.$_SERVER['SERVER_NAME'].'/rabbit.php?key='.$uuid;
       
        //上传图片
        $picUrl = $this->toUpload($picPath);      
        
    	$url = "http://".$this->url.":7000/FACSServer/rest/technicalFaces/queryPicByHistory";
        $score = '0.9';
        $picPath = $picUrl;
        $callBackUrl = 'technicalFaces/queryPicByHistoryRecord';
        $string = '';
    	foreach ($this->caID as $key => $value) {
    		$string .= '&crossIdList='.$value;
    	}
    	$urls = "$url?beginTime=".urlencode($beginTime)."&endTime=".urlencode($endTime)."&uuid=$uuid&callBackUrl=".urlencode($callBackUrl).$string."&score=$score&picPath=".urlencode($picPath);
       
        Tools::getHttp($urls);
       	Tools::getHttp($urlss);
        return 1;
        /*$data = json_decode($data,true); 
        if($data['ret'] == 0 && $data['count'] == 0){
            
            return 1;
        }
        return 0;*/
    }

    //上传到服务器
    public function toUpload($picPath){
        header('Content-Type: application/json');
        $imgUrl = $picPath;
        $URL = "http://".$this->url.":7000/FACSServer/rest/file/uploadFile";
        //如果php5.5以下
        //$data = array('media'=>'@'.$_SERVER['DOCUMENT_ROOT'].$imgUrl);
        //如果 php 5.6及以上
        $media = new \CURLFile($_SERVER['DOCUMENT_ROOT'].$imgUrl);

        $media->setMimeType("image/jpeg");
        $data  = array('upfile' => $media);
        $result = Tools::https_post($URL,$data);
        $result = strip_tags($result);
        $data = json_decode($result,true);
    
        return $data['content']['picUrl'];
            

    }
    //接收数据
    public function receive($data){
        
        //file_put_contents('text.txt',urldecode($data), FILE_APPEND | LOCK_EX);die;
        //$data = file_get_contents('text.txt');
        //$source = '{"uuid":"8a9d3c1d-4487-4fb4-8c42-e0590fc_1560","list":["http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65001\/2019\/03\/22\/14\/1553237977_1564.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/11\/1553227002_1444.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/13\/1553232421_3486.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/13\/1553232428_3491.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/11\/1553226988_1436.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/11\/1553226984_1435.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/22\/12\/1553228210_5826.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/22\/17\/1553247331_5762.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65000\/2019\/03\/18\/17\/1552901363_0002.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/13\/1553232438_3499.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65001\/2019\/03\/22\/14\/1553237949_1559.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65001\/2019\/03\/22\/14\/1553237950_1560.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/11\/1553226997_1440.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/14\/1553237906_3557.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/19\/14\/1552975481_0618.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/13\/1553232431_3494.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/11\/1553226975_1430.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/13\/1553232434_3495.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/25\/14\/1553494935_0704.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/25\/10\/1553479842_0185.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/11\/1553226969_1428.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/22\/15\/1553238016_3560.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/25\/10\/1553482178_0357.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/25\/12\/1553487715_0461.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/26\/17\/1553591856_7346.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65002\/2019\/03\/22\/14\/1553237943_2184.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/19\/12\/1552968536_0486.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/19\/13\/1552974528_0582.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/26\/17\/1553591636_7334.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/19\/13\/1552974856_0600.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/22\/10\/1553220359_2142.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/25\/16\/1553501618_0942.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65000\/2019\/03\/22\/14\/1553237918_2887.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/22\/10\/1553220433_2153.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/22\/16\/1553241762_4393.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65007\/2019\/03\/19\/13\/1552975109_0608.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/25\/14\/1553494488_0698.jpg","http:\/\/192.168.88.52:7000\/image\/data1\/NORMAL\/65003\/2019\/03\/22\/08\/1553216335_1931.jpg"]}';
        //dump($data);
        //$source = json_decode($source,true);
        $source = json_decode(urldecode($data),true);
        if(!empty($source)){
            $id = substr($source['uuid'],strpos($source['uuid'],'_')+1);
          
            foreach ($source['list'] as $key => $value) {
               $data_1[$key] = substr($value,strpos($value,':7000/')+5);
            }
            
            $data_1 = implode(',',$data_1);
            $data = ImgModel::where('s_big_path','in',$data_1)->field('img_id,qny_big_path')->select()->toArray();
          	if(!empty($data)){
                $mytask_id = MytaskModel::where('uid',$id)->where('type',2)->order('id desc')->value('id');
                file_put_contents('text1.txt',urldecode($mytask_id), FILE_APPEND | LOCK_EX);
                $this->adds($data,$id,$mytask_id);
                $this->insertAnser($id,$mytask_id,$data);

            }
            //$this->adds($data,$id);  
        }
    }

    //添加素材库
    public function adds($data,$user_id,$mytask_id){
        //halt($data);
       
        $array = [];
        foreach ($data as $key => $value) {
            $array[$key] = $value['qny_big_path'];
        }
        $data_m['images'] = implode(',',$array);
        $data_m['userId'] = $user_id;
        $data_m['mytask_id'] = $mytask_id;
        $data_m['title'] = '[大课堂]提示：你可以制作陶瓷艺术馆学习手册了。';
        $data_m['content'] = '[大课堂]提示：你可以制作陶瓷艺术馆学习手册了。';
        $data_m['format'] = 1;
        $data_m['type'] = 2;
        $data_m['createTime'] = date('Y-m-d H:i:s');
        $data_m['province'] = '北京市';
        $data_m['city'] = '北京市';
        $data_m['address'] = '北京陶瓷艺术馆';
        $MaterialModel = new MaterialModel();
        $MaterialModel->save($data_m);
        return 1;
    }
    /**
     * [更新素材库]
     * @param  [type] $userId [description]
     * @param  [type] $taskid  [课题ID]
     * @return [type]         [description]
     */
    public function insertAnser($userId,$taskid,$images){
        
        $progressid = 3;
        $t_id = MytaskModel::where('id',$taskid)->value('t_id');
       
        $classprogressid = ClassprogressModel::where('mid',$t_id)->where('progressid',$progressid)->value('id');
        $array = [];
        foreach ($images as $key => $value) {
            $array[$key] = '1|'.$value['qny_big_path'];
            if($key == 1){
                break;
            }
        }
        $data['content']  = implode(',',$array);
        $data['content'] = $data['content'].',&lt;&gt;';
        $data['activation_num'] = 2;
      
        $rs=db('anser')->where(['userId'=>$userId,'taskid'=>$taskid,'pid'=>$progressid,'classprogressid'=>$classprogressid])->update($data);
  
    }

    public function getLists(){
        $data = ImgModel::where('status',1)->limit(0,100)->select();
        foreach ($data as $key => $value) {
            $s_big_path = "http://".$this->url.':7001'.$value['s_big_path'];
            $base_big_path = $this->getImage($s_big_path);
            $data_img['base_big_path'] = $base_big_path['save_path'];
            
            //$s_path = "http://".$this->url.':7001'.$value['s_path'];
            //$s_path = $this->getImage($s_path);
            //$data_img['base_path'] = $s_path['save_path'];
            $data_img['status'] = 2;
            ImgModel::where('img_id',$value['img_id'])->update($data_img);
        }
    }


    //获取到本地，改变状态
    public function getList(){
        ImgStatusModel::where('day',date("Y-m-d"))->update(['status'=>2]);
        
    }

    //将本地上传到七牛云
    public function uploads(){

        $data = ImgModel::where('status',2)->limit(0,100)->select();
        $Qiniu = new Qiniu();
        foreach ($data as $key => $value) {
            $base_big_path = $value['base_big_path'];
            try{
                //获取远程文件所采用的方法 
                $data_img['qny_big_path'] = $Qiniu->index($base_big_path);
            }catch (\Exception $exception) {
                $data_img['qny_big_path'] = null;
            } catch(\Error $error) {
                $data_img['qny_big_path'] = null;
            }
        
            //$base_path = $value['base_path'];
            //$data_img['qny_path'] = $Qiniu->index($base_path);

            $data_img['status'] = 3;
            $data_img['upload_time'] = date('Y-m-d H:i:s');
            ImgModel::where('img_id',$value['img_id'])->update($data_img);
            
        }

    }
    //将本地上传到七牛云,改变状态
    public function upload(){

        ImgStatusModel::where('day',date("Y-m-d"))->update(['status'=>3]);
    }

    public function dels(){
        $data = ImgModel::where('status',3)->select();
        foreach ($data as $key => $value) {
            if (file_exists($value['base_big_path'])) {
                unlink($value['base_big_path']);
            }
            /*if (file_exists($value['base_path'])) {
                unlink($value['base_path']);
            }*/
            $data_img['status'] = 4;
            $data_img['del_time'] = date('Y-m-d H:i:s');
            ImgModel::where('img_id',$value['img_id'])->update($data_img);
        }
    }
    //删除本地图像
    public function del(){
        ImgStatusModel::where('day',date("Y-m-d"))->update(['status'=>4]);
        
    }

    //下载二维码图片
    public function getImage($url,$type=0){
        if(trim($url)==''){
            return array('file_name'=>'','save_path'=>'','error'=>1);
        }

        $save_dir='../upload/qinuy';
        
        $filename = $this->create_unique().".jpg";
        if(0!==strrpos($save_dir,'/')){
            $save_dir.='/';
        }
        //创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
            return array('file_name'=>'','save_path'=>'','error'=>5);
        }
        try{
             //获取远程文件所采用的方法 
            if($type){
                $img = (new Wxtools())->getHttp($url);
            }else{
                ob_start(); 
                readfile($url);
                $img=ob_get_contents(); 
                ob_end_clean(); 
            }
            $size=strlen($img);
            //文件大小 
            $fp2=@fopen($save_dir.$filename,'a');
            fwrite($fp2,$img);
            fclose($fp2);
            unset($img,$url);
            
            return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
        }catch (\Exception $exception) {
            return array('file_name'=>'','save_path'=>'','error'=>0);
        } catch(\Error $error) {
            return array('file_name'=>'','save_path'=>'','error'=>0);
        }
        
    }

    //生成文件名
    function create_unique() {
        $data = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']
         .time() . rand();
        return sha1($data);
    }

}
